#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "matrixprocessor.h"  // 包含算法处理器头文件
#include <QMessageBox>
#include <QTableWidgetItem>
#include <stdexcept>
#include <QVector>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , processor(new MatrixProcessor(this))  // 初始化算法处理器
    ,is(0)
{
    ui->setupUi(this);

    // 初始化表格属性
    ui->tableWidget->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
}

MainWindow::~MainWindow()
{
    delete ui;  // 自动删除processor（因指定parent为this）
}

// 生成网格按钮点击处理
void MainWindow::on_generateButton_clicked()
{
    const int rows = ui->rowSpinBox->value();
    const int cols = ui->colSpinBox->value();
    is = QVector<QVector<bool>>(rows, QVector<bool>(cols, true));

    // 清除旧数据
    ui->tableWidget->clear();
    ui->tableWidget->setRowCount(rows);
    ui->tableWidget->setColumnCount(cols);

    // 设置固定单元格尺寸（50x50像素）
    const int cellSize = 50;
    for(int i = 0; i < rows; ++i) {
        ui->tableWidget->setRowHeight(i, cellSize);
    }
    for(int j = 0; j < cols; ++j) {
        ui->tableWidget->setColumnWidth(j, cellSize);
    }

    // 初始化单元格
    for(int i = 0; i < rows; ++i) {
        for(int j = 0; j < cols; ++j) {
            QTableWidgetItem *item = new QTableWidgetItem();
            item->setTextAlignment(Qt::AlignCenter);
            item->setBackground(Qt::white);
            item->setFlags(item->flags() | Qt::ItemIsEditable);
            ui->tableWidget->setItem(i, j, item);
        }
    }
}

// 处理按钮点击事件
void MainWindow::on_processButton_clicked()
{
    if (!validateInput()) return;

    try {
        auto matrix = getCurrentMatrix();
        QList<QPoint> redCells = processor->processMatrix(matrix);

        resetAllCellsColor();
        markSpecialCells(redCells);
        updateCellTooltips();  // 新增工具提示更新

    } catch (const std::exception& e) {
        QMessageBox::critical(this, "处理错误", e.what());
    }
}

// 输入验证函数
bool MainWindow::validateInput()
{
    const int rows = ui->tableWidget->rowCount();
    const int cols = ui->tableWidget->columnCount();

    // 检查空表格
    if (rows == 0 || cols == 0) {
        QMessageBox::warning(this, "输入错误", "请先生成网格");
        return false;
    }

    // 检查每个单元格
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            QTableWidgetItem* item = ui->tableWidget->item(i, j);

            // 检查是否存在空项
            if (!item || item->text().isEmpty()) {
                QMessageBox::warning(this, "输入不完整",
                                     QString("第%1行第%2列未填写").arg(i+1).arg(j+1));
                return false;
            }

            // 检查是否为有效整数
            bool ok;
            item->text().toInt(&ok);
            if (!ok) {
                QMessageBox::warning(this, "输入错误",
                                     QString("第%1行第%2列包含非数字内容").arg(i+1).arg(j+1));
                return false;
            }
        }
    }
    return true;
}

// 获取当前矩阵数据
MainWindow::Matrix MainWindow::getCurrentMatrix() const
{
    const int rows = ui->tableWidget->rowCount();
    const int cols = ui->tableWidget->columnCount();
    Matrix matrix(rows, std::vector<int>(cols));

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            matrix[i][j] = item->text().toInt();
        }
    }
    return matrix;
}

// 重置所有单元格颜色为白色
void MainWindow::resetAllCellsColor()
{
    const int rows = ui->tableWidget->rowCount();
    const int cols = ui->tableWidget->columnCount();

    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            if (QTableWidgetItem* item = ui->tableWidget->item(i, j)) {
                item->setBackground(Qt::white);
            }
        }
    }
}

// 标记特定单元格（使用红色高亮）
void MainWindow::markSpecialCells(const QList<QPoint>& points)
{
    const QColor highlightColor = Qt::red;

    for (const QPoint& p : points) {
        const int row = p.y();  // QPoint的y对应行索引
        const int col = p.x();  // QPoint的x对应列索引

        // 检查坐标有效性
        if (row < 0 || row >= ui->tableWidget->rowCount() ||
            col < 0 || col >= ui->tableWidget->columnCount())
        {
            throw std::out_of_range("处理器返回了无效的单元格坐标");
        }

        if (QTableWidgetItem* item = ui->tableWidget->item(row, col)) {
            item->setBackground(highlightColor);
        }
    }
}



int MainWindow::calculateSurroundingSum(int row, int col)
{
    const QList<QPoint> directions = {
        {0, -1},  // 上
        {0, 1},   // 下
        {-1, 0},  // 左
        {1, 0}    // 右
    };

    int sum = 0;

    foreach (const QPoint& dir, directions) {
        int r = row + dir.y();
        int c = col + dir.x();

        // 边界检查
        if(r < 0 || r >= ui->tableWidget->rowCount() ||
            c < 0 || c >= ui->tableWidget->columnCount())
        {
            continue;
        }

        QTableWidgetItem* neighbor = ui->tableWidget->item(r, c);
        if(neighbor && neighbor->background() != Qt::red) {
            bool ok;
            int value = neighbor->text().toInt(&ok);
            if(is[r][c])
            {
                is[r][c]= false;
                sum += value;
                neighbor->setBackground(Qt::yellow);
            }
        }
    }

    return sum;
}

void MainWindow::updateCellTooltips()
{
    const int rows = ui->tableWidget->rowCount();
    const int cols = ui->tableWidget->columnCount();
    int ans=0;
    for(int i = 0; i < rows; ++i) {
        for(int j = 0; j < cols; ++j) {
            QTableWidgetItem* item = ui->tableWidget->item(i, j);
            if(item && item->background() == Qt::red) {
                int sum = calculateSurroundingSum(i, j);
                ans+=sum;
                item->setToolTip(QString("周围非红格子之和: %1").arg(sum));
            }
        }
    }
    QMessageBox::information(this,QString("最大数") ,
                         QString("最优策略的值为: %1").arg(ans));
}
